const { existsSync, mkdirSync, readdir, unlinkSync, writeFileSync, readdirSync } = require('fs')
const { resolve } = require('path')

const templateReg = /\<template\>(.*?)\<\/template\>/
const scriptReg = /\<script\>(.*?)\<\/script\>/
const styleReg = /<style>/

function vueLoader(source) {
  const _str = source.replace(/[\r\n]/g, '')

  const template = getTagContent('template', _str)
  const script = getTagContent('script', _str)
  const style = getTagContent('style', _str)
  const cssFileName = `/_temp/css/_css${new Date().getTime()}.css`

  const vueScript = script.replace(/\{/, `{ template: '${template}',`)
  writeFile(cssFileName, style)

  return `
    import '${cssFileName}'
    ${vueScript}
  `
}

function getTagContent(tagName, text) {
  const _reg = new RegExp(`<${tagName}>(.*?)</${tagName}>`, 'i')
  return text.match(_reg)[1]
}

function writeFile(fileName, content) {
  if (!existsSync(formatPath('../../_temp'))) {
    mkdirSync(formatPath('../../_temp'))
    mkdirSync(formatPath('../../_temp/css'))
  }

  const files = readdirSync(formatPath('../../_temp/css'))
  files && files.forEach(file => {
    unlinkSync(formatPath('../../_temp/css/' + file))
  })

  writeFileSync(formatPath('../../' + fileName), content)
}

function formatPath(path) {
  return resolve(__dirname, path)
}

module.exports = vueLoader